<script setup>
	import {ref, computed, defineProps, reactive} from "vue"

	const centerDialogVisible = ref(false)
	import lodash from "lodash"
	import zhCn from 'element-plus/es/locale/lang/zh-cn'
	import {formatTimestamp} from "@/tools/common"

	const props = defineProps({
		columns: {
			typeof: Array,
			require: true,
		},
		request: {
			typeof: Function,
			require: true,
		},
		ispagination: {
			typeof: Boolean,
			default: true,
		},
		editApi: {
			typeof: Function,
		},
		delApi: {
			typeof: Function,
		},
	})
	const locale = ref(zhCn)
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val
	}
	const tableData = ref([])
	const pagedata = reactive({
		page: 1, // 页码
		pageSize: 10, // 每页查询记录数
		total: 0,
		totalPages: 0,
	})
	//  计算属性  可被编辑的属性
	const editList = computed(() => {
		return props.columns.filter((item) => {
			if (item.isEdit) {
				return item
			}
		})
	})
	const requestData = () => {
		props.request({page: pagedata.page, pageSize: pagedata.pageSize})
				.then((res) => {
					try {
						if (res.code === 200) {
							console.log(res.data)
							pagedata.page = res.data.page
							pagedata.total = res.data.total
							pagedata.totalPages = res.data.totalPages
							tableData.value = res.data.list
						}
					} catch (error) {
						throw new Error(error)
					}
				})
	}
	requestData()
	/**
	 * 翻页操作
	 */
	const handleCurrentChange = (page) => {
		pagedata.page = page
		requestData()
	}
	/**
	 * 切换每页查询数据量
	 */
	const handleSizeChange = (pageSize) => {
		pagedata.pageSize = pageSize
		requestData()
	}

	/**
	 *  编辑每一行的数据
	 */
	const formData = ref({})
	const handleClick = (row) => {
		// 深拷贝
		formData.value = lodash.cloneDeep(row)
		centerDialogVisible.value = true
	}

	const edit = (form) => {
		props.editApi(form).then((res) => {
			console.log(res)
			if (res.code === 200) {
				requestData()
				ElMessage.success(res.msg)
				centerDialogVisible.value = false
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	/**
	 *  导出
	 */
	// const exportExcel = () => {
	// 	const headers = props.columns.map((col) => col.label)
	// 	const data = [
	// 		headers,
	// 		...tableData.value.map((row) => props.columns.map((col) => row[col.prop])),
	// 	]
	// 	const worksheet = XLSX.utils.json_to_sheet(data, {skipHeader: true})
	// 	const workbook = XLSX.utils.book_new()
	// 	XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1")
	//
	// 	// Export the file
	// 	XLSX.writeFile(workbook, `${route.name}.xlsx`)
	// }

	/**
	 *  搜索
	 */
	const searchValue = ref("")
	const search = () => {
		props.request({page: 1, pageSize: 20, searchValue: searchValue.value})
				.then((res) => {
					if (res.code === 200) {
						console.log(res.data)
						pagedata.page = res.data.page
						pagedata.total = res.data.total
						pagedata.totalPages = res.data.totalPages
						tableData.value = res.data.list
					}
				})
	}
	/**
	 *  新增loading
	 *  删除
	 */
	const deleteClick = (row) => {
		ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			props.delApi({_id: row._id,})
					.then((res) => {
						if (res.code === 200) {
							requestData()
							ElMessage.success(res.msg)
						} else {
							ElMessage.error(res.msg)
						}
					})
		})
	}

	// 重置按钮
	const reset = () => {
		props.request({page: 1, pageSize: 20}).then((res) => {
			try {
				if (res.code === 200) {
					console.log(res.data)
					pagedata.page = res.data.page
					pagedata.total = res.data.total
					pagedata.totalPages = res.data.totalPages
					tableData.value = res.data.list
				}
			} catch (error) {
				throw new Error(error)
			}
		})
	}
</script>
<template>
	<main>
		<div class="table-top">
			<!-- 操作  导出   搜索 -->
			<slot name="controls"></slot>
			<!--			<el-button type="primary" @click="exportExcel">导出</el-button>-->
			<div>
				<el-input
						v-model="searchValue"
						placeholder="请输入搜索内容"
						clearable
						class="input-with-select"
						style="width: 300px; margin-right: 10px"
				>
				</el-input>
				<el-button type="primary" @click="search">搜索</el-button>
				<el-button type="primary" @click="reset">重置</el-button>
			</div>
		</div>
		<el-table
				:data="tableData"
				stripe
				:default-sort="{ prop: 'date', order: 'descending' }"
				@selection-change="handleSelectionChange"
				:show-overflow-tooltip="true"
		>
			<el-table-column fixed type="selection" width="40"/>
			<el-table-column
					v-for="col in props.columns"
					:prop="col.prop"
					:label="col.label"
					:key="col.prop"
					:sortable="col.prop === 'date'"
					:min-width="col.width ? col.width : 100"
					fit="auto"
			>
				<template #default="{ row }">
					<!-- 判断是否是 status 列，是的话插入 el-switch -->
					<el-switch
							v-if="col.prop === 'status'"
							v-model="row.status"
							disabled
							style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; "
					/>
					<div v-else-if="col.prop === 'img' || col.prop === 'avatar'">
						<img
								:src="row[col.prop]"
								alt=""
								style="width: 100px; height: 100px"/>
					</div>
					<div v-else-if="col.prop === 'password'">
						<el-input v-model="row[col.prop]" type="password" show-password/>
					</div>
					<div v-else-if="col.prop === 'createTime'">
						{{ formatTimestamp(row[col.prop], 'YYYY-MM-dd ') }}
					</div>
					<!-- 如果不是 status 列，显示原始内容 -->
					<div v-else>{{ row[col.prop] }}</div>
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作" width="180">
				<template #default="{ row }">
					<el-button
							type="primary"
							v-if="props.editApi"
							size="small"
							@click="handleClick(row)"
					>编辑
					</el-button>
					<el-button
							type="danger"
							v-if="props.delApi"
							size="small"
							@click="deleteClick(row)"
					>删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页器 -->
		<el-config-provider :locale="locale" v-if="ispagination">
			<el-pagination
					background
					:hide-on-single-page="false"
					:total="pagedata.total"
					:page-size="pagedata.pageSize"
					:current-page="pagedata.page"
					layout="total,sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
			></el-pagination>
		</el-config-provider>
	</main>

	<!--	编辑页面-->
	<el-dialog
			v-model="centerDialogVisible"
			title="编辑"
			width="800"
			align-center
	>
		<main>
			<el-form :model="formData" label-width="auto" style="max-width: 800px">
				<el-form-item
						:label="col.label"
						v-for="col in editList"
						:key="col.prop"
				>
					<template v-if="col.isEdit">
						<el-input
								v-model="formData[col.prop]"
								v-if="col.prop !== 'status'"
						/>
						<el-switch
								v-if="col.prop === 'status'"
								v-model="formData[col.prop]"
								style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
						/>
					</template>
				</el-form-item>
			</el-form>
		</main>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="centerDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="edit(formData)"> 确认</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style lang="scss" scoped>
	main {
		padding: 8px;
	}

	.table-top {
		height: 40px;
		line-height: 40px;
		align-items: center;
		display: flex;
		gap: 20px;
		background: var(--background-color);
	}

	.el-table {
		width: 100%;
		margin-top: 10px;
		min-height: 500px;
	}

	.el-pagination {
		margin-top: 20px;
		padding-bottom: 20px;
		width: 400px;
		position: relative;
		left: calc(50% - 300px);
	}

	.table-top {
		padding-left: 20px;
	}

	:deep(.el-table .cell) {
		white-space: nowrap;
	}

	:deep(.el-table__row) {
		height: 80px;
	}

	:deep(.cell div) {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>
